package com.cloudfunx.common.util;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cloudfunx.common.exception.BizException;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;

import java.io.Serializable;

@Data
public class PageRequest<F> implements Serializable {
    private static final long serialVersionUID = -4976202359298582250L;
    private Integer current = 1;
    private Integer size = 20;

    private Long total = -1L;

    private F filter;

    private String sort;

    private boolean isAsc = false;

    /**
     * 是否排序
     */
    private boolean needSort = true;

    private static final String DEFAULT_SORT_FIELD = "create_time";

    public PageRequest<F> buildNextPage() {
        return this.buildNextPage(this.total);
    }

    public PageRequest<F> buildNextPage(Long total) {
        PageRequest<F> next = new PageRequest<>();
        next.setCurrent(this.current + 1);
        next.setSize(this.size);
        next.setFilter(this.filter);
        next.setSort(this.sort);
        next.setTotal(total);
        return next;
    }

    public Page<F> buildPage() {
        Page<F> page = new Page<>(current, size);
        return build(page);
    }

    public Page<F> buildPage(String orderField) {
        if (StringUtils.isNotBlank(orderField)) {
            setSort(orderField);
        }
        return this.buildPage();
    }

    public Page<F> buildPage(String orderField, boolean isAsc) {
        if (StringUtils.isNotBlank(orderField)) {
            setSort(orderField);
            setAsc(isAsc);
        }
        return this.buildPage();
    }

    public <T> Page<T> buildPage(Class<T> cla) {
        Page<T> page = new Page<>(current, size);
        return build(page);

    }

    private <T> Page<T> build(Page<T> page) {
        if (needSort) {
            if (sort != null && !"".equals(sort)) {
                if (isAsc) {
                    page.setAsc(sort);
                } else {
                    page.setDesc(sort);
                }
            } else {
                page.setDesc(DEFAULT_SORT_FIELD);
            }
        }
        return page;
    }

    public <T> T ofFilter(Class<T> cla) {
        F filter = getFilter();
        if (null != filter) {
            try {

                T t = cla.newInstance();
                //T t = BeanUtils.instantiateClass(cla);
                BeanUtils.copyProperties(filter, t);
                return t;

            } catch (Exception e) {
                return null;
            }


        }
        return null;
    }

    public F getFilter(Class<F> clazz) {
        try {
            return filter == null ? clazz.newInstance() : filter;
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
            throw new BizException("filter 错误");
        }
    }
}
